//
//  AppScriptMessageHandler.swift
//  
//
//  Created by tank on 2021/12/4.
//

import Foundation
import WebKit

class AppScriptMessageHandler: NSObject, WKScriptMessageHandler {

    static let key: String = "app"

    var webViewHandlers: [String: WebViewHandlerProtocol] = [
        CloseDialogHandler.id: CloseDialogHandler(),
        RequestHandler.id: RequestHandler(),
        AlertHandler.id: AlertHandler(),
        ConfirmHandler.id: ConfirmHandler(),
        SetRightMenusHandler.id: SetRightMenusHandler(),
        ShareHandler.id: ShareHandler(),
        PostWebViewMessageHandler.id: PostWebViewMessageHandler()
    ]

    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {

        guard let values = message.body as? [String: Any], let id = values["id"] as? String else {
            return
        }

        guard let handler = webViewHandlers[id] else {
            return
        }

        handler.handler(handler,
                        webView: message.webView as? WKWebViewEx,
                        frameInfo: message.frameInfo,
                        params: values["params"] as? [String: Any])
    }
}
